package com.zhouwr.common.metadata;

import com.zhouwr.common.enums.ModelDataType;
import com.zhouwr.common.utils.HexConvertUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * @program: forallcn-iotps
 * @description:
 * @author: zhouwr
 * @create: 2020-11-26 22:42
 * @version：1.0
 **/
@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class ByteData extends AbstractData<ByteData> implements DataType, Converter<Byte>{
    private Byte value = 0x0;
    private ModelDataType type =  ModelDataType.BYTE;

    @Override
    public Byte convert(Object value) {
        if(value instanceof String) {
            // 字符类型，原样转换，如'01'->01
            this.value = Objects.requireNonNull(HexConvertUtil.hexStringToBytes(value + ""))[0];
            log.info("{}->{}", value, this.value);
        } else if(value instanceof Integer) {
            this.value = ((Integer) value).byteValue();
        } else {
            this.value = (Byte) value;
        }
        return this.value;
    }

    @Override
    public String format(Object value) {
        byte[] bytes = new byte[]{(byte) value};
        return StringUtils.trimToEmpty(HexConvertUtil.BinaryToHexString(bytes));
    }

    @Override
    public ValidateResult validate(Object value) {
        return ValidateResult.success(Byte.valueOf(value.toString()));
    }

    public static void main(String[] args) {
        ByteData b = new ByteData();
        b.convert("d");
        System.out.println(b);
    }
}
